<?php
require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/Logger.php';

/**
 * 关键词管理类
 */
class KeywordManager
{
    private $db;
    private $logger;
    
    public function __construct($config = null)
    {
        $this->db = Database::getInstance();
        $this->logger = new Logger($config);
    }
    
    /**
     * 随机获取一个未读取的关键词并标记为已读
     * @return string|null 返回关键词，如果没有则返回null
     */
    public function getRandomUnreadKeyword()
    {
        try {
            // 开始事务
            $this->db->getConnection()->beginTransaction();
            
            // 随机获取一个未读取的关键词
            $sql = "SELECT id, keyword FROM keyword WHERE is_read = 0 ORDER BY RAND() LIMIT 1";
            $keyword = $this->db->fetchOne($sql);
            
            if (!$keyword) {
                $this->db->getConnection()->rollBack();
                return null;
            }
            
            // 标记为已读
            $updateSql = "UPDATE keyword SET is_read = 1 WHERE id = ?";
            $this->db->query($updateSql, [$keyword['id']]);
            
            $this->db->getConnection()->commit();
            
            return $keyword['keyword'];
        } catch (Exception $e) {
            $this->db->getConnection()->rollBack();
            throw new Exception("获取关键词失败: " . $e->getMessage());
        }
    }
    
    /**
     * 批量插入关联关键词
     * @param array $keywords 关键词数组
     * @return bool 是否成功
     */
    public function insertRelatedKeywords($keywords)
    {
        if (empty($keywords)) {
            return true;
        }
        
        try {
            $sql = "INSERT INTO keyword (keyword, type, is_read) VALUES (?, '关联关键词', 0)";
            $stmt = $this->db->getConnection()->prepare($sql);
            
            foreach ($keywords as $keyword) {
                $keyword = trim($keyword);
                if (!empty($keyword)) {
                    $stmt->execute([$keyword]);
                }
            }
            
            return true;
        } catch (Exception $e) {
            throw new Exception("保存关联关键词失败: " . $e->getMessage());
        }
    }
    
    /**
     * 获取所有未读取的关键词数量
     * @return int
     */
    public function getUnreadKeywordCount()
    {
        $sql = "SELECT COUNT(*) as count FROM keyword WHERE is_read = 0";
        $result = $this->db->fetchOne($sql);
        return (int)$result['count'];
    }
    
    /**
     * 重置所有关键词为未读状态（用于测试）
     * @return bool
     */
    public function resetAllKeywords()
    {
        try {
            $sql = "UPDATE keyword SET is_read = 0";
            $this->db->query($sql);
            return true;
        } catch (Exception $e) {
            throw new Exception("重置关键词失败: " . $e->getMessage());
        }
    }
}
